package com.example.cinema.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;

import com.example.cinema.BR;
import com.example.cinema.R;
import com.example.cinema.UserAttribute;
import com.example.cinema.bindingdata.PlayerData;
import com.example.cinema.databinding.ActivityPlayerBinding;
import com.example.cinema.drawview.VideoPlayer;
import com.example.cinema.fragment.VideoAppraise;
import com.example.cinema.request.RequestData;
import com.example.cinema.request.RequestSend;
import com.example.cinema.testdara.TestData;
import com.example.cinema.toolclass.AmbientInspect;
import com.example.cinema.toolclass.TimeTransform;
import com.google.zxing.common.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class ActivityVideoPlayer extends AppCompatActivity {


    @Override
    protected void onResume() {
        super.onResume();
        if (APB.videoplayer.mediaPlayer != null) {
            APB.videoplayer.mediaPlayer.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (APB.videoplayer.mediaPlayer != null) {
            APB.videoplayer.mediaPlayer.pause();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (APB.videoplayer.mediaPlayer != null) {
            APB.videoplayer.mediaPlayer.stop();
            APB.videoplayer.mediaPlayer.release();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            int or = getResources().getConfiguration().orientation;
            if (or == 2) {
                Suo();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    ActivityPlayerBinding APB;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        APB = DataBindingUtil.setContentView(this, R.layout.activity_player);
        initdata();
        init();

        initlistener();

        if(Build.VERSION.SDK_INT>11 && Build.VERSION.SDK_INT<19)
        {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        }else if(Build.VERSION.SDK_INT>=19){
            View view = getWindow().getDecorView();
            int UIOP = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY|View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(UIOP);
        }
    }

    private String vid;
    private String tid;
    private String imglist;
    private String plurl;
    private boolean vipbool;
    private void initdata() {
        attribute = (UserAttribute) getApplication();
        pdata = new PlayerData();
        //获取传递的PID
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        String title = bundle.getString("title");
        vid = bundle.getString("vid");
        tid = bundle.getString("type");
        String brief = bundle.getString("brief");
        String urls = bundle.getString("urls");
        String surl = bundle.getString("shorturl");
        Log.i("GGGG", urls);
        imglist = bundle.getString("imglist");
        String uimg = bundle.getString("uimg");
        String number = bundle.getString("love");
        vipbool = bundle.getBoolean("bool");
        pdata.videolove.set(number);
        pdata.titles.set(title);
        pdata.videovid.set(vid);
        pdata.videotype.set(tid);
        pdata.videobrief.set(brief);
        pdata.videoshort.set(surl);
        pdata.playerurl.set(urls);
        pdata.userimg.set(uimg);
        Log.i("KJJJ",vipbool+"");
        if(vipbool)
        {
            try {
                plurl = urls+"?token="+ URLEncoder.encode(attribute.getToken(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            Log.i("KJJJ",plurl);
        }else {
            plurl = surl;
            Log.i("KJJJ",plurl);
        }

    }

    private PlayerData pdata;
    private UserAttribute attribute;

    private void init() {

        APB.setVariable(BR.playerdatas, pdata);
        APB.startbtn.getDrawable().setLevel(2);
        APB.startbtna.getDrawable().setLevel(2);
        APB.allping.getDrawable().setLevel(1);

        getDataPlayer();

        addFragment();
        listenerinit();
    }

    //获取播放数据并播放
    private void getDataPlayer() {
        new Thread() {
            @Override
            public void run() {
                if (plurl != null) {
                    APB.videoplayer.SetUrlPlayer(plurl);
                    APB.videoplayer.loadVideo(plurl);
                    TaskAsyn();
                }
            }
        }.start();
    }

    //添加模块
    VideoAppraise appraise;

    public void addFragment() {
        appraise = new VideoAppraise();

        appraise.setVideid(vid, tid);
        FragmentManager Fm = getSupportFragmentManager();
        FragmentTransaction Ft = Fm.beginTransaction();
        Ft.add(R.id.lineragrid, appraise);
        Ft.commit();

        appraise.SetListCountIsNull(new VideoAppraise.ListCountIsNullListener() {
            @Override
            public void IsNull(boolean abool) {
                if(abool)
                {
                    TextView textView = new TextView(getApplicationContext());

                    textView.setText("暂无用户评价！快留下您的足迹！");
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    params.gravity= Gravity.CENTER;
                    textView.setLayoutParams(params);
                    APB.lineragrid.addView(textView);
                }else {
                    APB.lineragrid.removeViewAt(0);
                }
            }
        });
    }

    //初始化监听
    public void listenerinit() {
        //点赞监听
        APB.zan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView iv = (ImageView) v;
                iv.getDrawable().setLevel(2);
                VideoZan();
            }
        });
    }

    boolean aBoolean = false;

    private void VideoZan() {
        new Thread() {
            @Override
            public void run() {
                RequestSend requestSend = new RequestSend(getApplicationContext());
                aBoolean = requestSend.SendVideoZan(vid);
                handler.sendEmptyMessage(1002);
            }
        }.start();
    }

    Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1000) {
                if (isSendReutl) {
                    Toast toast = Toast.makeText(getApplicationContext(), "评价成功", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                    APB.textsend.setText(null);
                    appraise.SetAssess(texts, attribute);
                } else {
                    Toast toast = Toast.makeText(getApplicationContext(), "评价失败", Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            }
            if (msg.what == 1002) {
                if (aBoolean) {
                    int in = Integer.valueOf(pdata.videolove.get());
                    pdata.videolove.set(String.valueOf(in + 1));
                }
            }

            if(msg.what == 1003)
            {
                APB.mask.setVisibility(View.VISIBLE);
            }
        }
    };
    /*******************************************************/
    //线程读取当前时间进度
    private boolean isfor = true;

    private void TaskAsyn() {
        new Thread() {
            @Override
            public void run() {
                while (isfor) {
                    long cur = APB.videoplayer.current();
                    String tme = TimeTransform.timetf(cur);
                    pdata.currenttime.set(tme);
                    APB.seekbars.setProgress((int) cur);
                    Log.i("KKKK", cur + "");
                    try {
                        sleep(800);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.i("KKKK",  pdata.totalprogress.get()+"");
                    if(APB.videoplayer.mediaPlayer==null)
                    {
                        continue;
                    }
                    if(!APB.videoplayer.mediaPlayer.isPlaying())
                    {
                        Log.i("QQQS","播放结束");
                        Log.i("QQQS","状态"+vipbool);
                        if(!vipbool){
                            handler.sendEmptyMessage(1003);
                        }
                        isfor =false;
                    }
                }
            }
        }.start();
    }

    //事件监听
    private boolean isClick = true;
    private boolean isSendReutl;
    private String texts;

    private void initlistener() {
        //返回点击
        APB.finsh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //发送评论点击监听
        APB.send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                texts = APB.textsend.getText().toString();
                if (texts.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "请输入评论", Toast.LENGTH_LONG).show();
                    return;
                }
                //发送
                new Thread() {
                    @Override
                    public void run() {
                        RequestSend send = new RequestSend(getApplicationContext());
                        isSendReutl = send.SendAssess(vid, attribute.getUID(), texts);
                        handler.sendEmptyMessage(1000);
                    }
                }.start();
            }
        });
        //中心播放按钮监听
        APB.startbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("hhhh", "有效点击");
                if (APB.videoplayer.getplaystate()) {
                    APB.startbtn.getDrawable().setLevel(1);
                    APB.startbtna.getDrawable().setLevel(1);
                    Log.i("hhhh", "2");
                    APB.videoplayer.shtopplay();
                } else {
                    APB.startbtn.getDrawable().setLevel(2);
                    APB.startbtna.getDrawable().setLevel(2);
                    Log.i("hhhh", "1");
                    APB.videoplayer.startplay();
                }
            }
        });
        //控制台按钮监听
        APB.startbtna.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (APB.videoplayer.getplaystate()) {
                    APB.startbtn.getDrawable().setLevel(1);
                    APB.startbtna.getDrawable().setLevel(1);
                    APB.videoplayer.shtopplay();
                } else {
                    APB.startbtn.getDrawable().setLevel(2);
                    APB.startbtna.getDrawable().setLevel(2);
                    APB.videoplayer.startplay();
                }
            }
        });
        //播放器信息监听
        APB.videoplayer.setOnVideoPlayerInfo(new VideoPlayer.VideoPlayerInfo() {
            @Override
            public void PlayerInfo(long total) {
                pdata.totalprogress.set((int) total);
                Log.i("SSS", total + "");
                String tm = TimeTransform.timetf(total);
                pdata.totaltime.set(tm);
            }

        });
        //进度滑动
        APB.seekbars.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            private boolean isuser;

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                isuser = fromUser;
                if (fromUser) {
                    isfor = true;
                    APB.videoplayer.setProess(progress);
                    TaskAsyn();
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (isuser) {
                    isfor = false;
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //播放器容器点击监听
        APB.videoplayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isClick) {
                    isClick = false;
                    APB.console.setVisibility(View.GONE);
                    APB.startbtn.setVisibility(View.GONE);
                    APB.toplayout.setVisibility(View.GONE);
                } else {
                    isClick = true;
                    APB.console.setVisibility(View.VISIBLE);
                    APB.startbtn.setVisibility(View.VISIBLE);
                    APB.toplayout.setVisibility(View.VISIBLE);
                }
            }
        });
        //全屏点击
        APB.allping.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                int or = getResources().getConfiguration().orientation;
                if (or == 1) {
                    APB.toplayout.setVisibility(View.GONE);
                    hidevs();
                    fang();

                }
                if (or == 2) {
                    APB.toplayout.setVisibility(View.VISIBLE);
                    Suo();
                }
            }
        });
        //VIP提示点击
        APB.Maskbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("cartpay");
                startActivity(intent);
            }
        });
    }

    //屏幕缩放
    private int height = 0;

    private void Suo() {
        int w = getResources().getDisplayMetrics().widthPixels;
        APB.videolayout.setMinimumHeight(height);
        APB.videolayout.setMinimumWidth(w);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        APB.videoplayer.narrow(height);
        APB.sendpj.setVisibility(View.VISIBLE);
    }

    private void fang() {
        int w = getResources().getDisplayMetrics().widthPixels;
        int h = getResources().getDisplayMetrics().heightPixels;
        height = APB.videolayout.getHeight();
        APB.videolayout.setMinimumHeight(h);
        APB.videolayout.setMinimumWidth(w);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        APB.videoplayer.allquan();
        APB.sendpj.setVisibility(View.GONE);
    }

    //隐藏状态栏以及虚拟按键
    private void hidevs() {
        WindowManager.LayoutParams attrs = getWindow().getAttributes();
        attrs.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
        getWindow().setAttributes(attrs);


        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            View view = getWindow().getDecorView();
            view.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT > 19) {
            View view = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            view.setSystemUiVisibility(uiOptions);
        }
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        WindowManager.LayoutParams lp =getWindow().getAttributes();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lp.layoutInDisplayCutoutMode
                    =WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
        }
        getWindow().setAttributes(lp);


    }
}
